import type { App } from 'vue'
import XEUtils from 'xe-utils'
import VxeTable from 'vxe-table'
import 'vxe-table/lib/style.css'
import zhCN from 'vxe-table/es/locale/lang/zh-CN'
import VXETablePluginElement from 'vxe-table-plugin-element'
import 'vxe-table-plugin-element/dist/style.css'

// 按需加载的方式默认是不带国际化的，自定义国际化需要自行解析占位符 '{0}'，例如：
VxeTable.setConfig({
  zIndex: 3000,
  i18n: (key, args) => XEUtils.toFormatString(XEUtils.get(zhCN, key), args)
})

VxeTable.use(VXETablePluginElement)

function getEventTargetNode(evnt: any, container: any, className: any) {
  let targetElem: any
  let target = evnt.target
  while (target && target.nodeType && target !== document) {
    if (
      className &&
      target.className &&
      target.className.split &&
      target.className.split(' ').indexOf(className) > -1
    ) {
      targetElem = target
    } else if (target === container) {
      return {
        flag: className ? !!targetElem : true,
        container: container,
        targetElem: targetElem
      }
    }
    target = target.parentNode
  }
  return {
    flag: false
  }
}

VxeTable.interceptor.add('event.clearEdit', (params) => {
  const { $event } = params
  // 比如点击了某个组件的弹出层面板之后，此时被激活单元格不应该被自动关闭，通过返回 false 可以阻止默认的行为。
  const bodyElem = document.body
  if (getEventTargetNode($event, bodyElem, 'ck-body-wrapper')?.flag) return false
})

function useTable(app: App) {
  // 可选组件
  app.use(VxeTable)
}

export const setupVxeTable = (app: App<Element>): void => {
  app.use(useTable)
}
